package com.zg.exercise

import com.google.gson.GsonBuilder
import com.zg.ktcomwan.data.IApiService
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/***
 * @Author:      zxd
 * @CreateDate:  2021/6/2 8:50
 * @Description:
 */
class ApiUtils {

    companion object {

        private val okHttpBuilder: OkHttpClient.Builder
            get() {
                val httpClient = OkHttpClient.Builder()
                    .addInterceptor(Interceptor { chain ->
                        val original = chain.request()
                        val request = original.newBuilder()
                            .header("Accept", "application/json")
                            .method(original.method, original.body)
                            .build()
                        return@Interceptor chain.proceed(request)
                    })
                    .readTimeout(30, TimeUnit.SECONDS)
                // log interceptor
                val loggingInterceptor = HttpLoggingInterceptor()
                loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                httpClient.addInterceptor(loggingInterceptor)
                return httpClient
            }

        // core for controller
        val service: IApiService = create(IApiService::class.java)

        lateinit var retrofit: Retrofit

        public fun <T> create(serviceClass: Class<T>): T {
            val gson = GsonBuilder()
                .serializeNulls()
                .create()

            // create retrofit
            retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl("https://www.wanandroid.com/") // Put your base URL
                .client(okHttpBuilder.build())
                .build()
            return retrofit.create(serviceClass)
        }
    }
}